<template>
  <div>
    <div class="headHint">活动图片</div>
    <el-row>
      <el-col :span="10">
        <el-input v-model="secondKeyWord" clearable style="width:200px" placeholder="请输入搜索内容" @clear="handleFilter" @keyup.enter.native="handleFilter"/>
        <el-button type="primary" style="margin-left:10px;" @click="handleFilter">搜索</el-button>
      </el-col>
      <el-col :span="2" :offset="12">
        <el-button type="primary" icon="el-icon-plus" @click="addsecondActivity">新增图片</el-button>
      </el-col>
    </el-row>
    <el-table
      :data="pictureTableData.slice((secondCurrentPage-1)*secondPageSize,secondCurrentPage*secondPageSize)"
      :default-sort="{prop: 'typeIndex', order: 'ascending'}"
      border
      style="width: 100%;text-align:center;margin-top:20px;">
      <el-table-column :index="typeIndex" type="index" label="编号" align="center" width="100"/>
      <el-table-column prop="fileName" label="图片名称" sortable column-key="fileName" align="center"/>
      <el-table-column prop="fileUrl" label="图片展示" sortable column-key="fileUrl" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.fileUrl" :src="scope.row.fileUrl" style="width:100px;height:100px;">
          <span v-if="!scope.row.fileUrl">未上传</span>
        </template>
      </el-table-column>
      <el-table-column prop="memo" label="备注" sortable column-key="memo" align="center"/>
      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="editPicture(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="deletePicture(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block" style="margin:20px 0;">
      <el-pagination
        :current-page="secondCurrentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="secondPageSize"
        :total="pictureTableData.length"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <!-- 新增/编辑活动弹框 -->
    <el-dialog :visible.sync="addActivityDialogVisible" :before-close="addCancelDialogVisible" title="活动图片" width="30%">
      <div style="margin:20px 0;">
        <span style="width:100px;text-align:right;margin-right:20px;display:inline-block;">图片:</span>
        <el-upload
          :on-change="addUploadChange"
          :http-request="submitUpload"
          :limit="1"
          :file-list="normal"
          action=""
          class="upload-demo"
          accept="image/jpg, image/png"
          style="width:60%;display: inline-block;vertical-align: top;margin-top: -8px;"
        >
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
        </el-upload>
        <img v-if="activityPicForm.fileUrl" :src="activityPicForm.fileUrl" style="width: 40%;margin-left: 120px;">
      </div>
      <div>
        <span style="width:100px;text-align:right;margin-right:20px;display:inline-block;">备注:</span>
        <el-input v-model="activityPicForm.memo" style="width: 60%;"/>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCancelDialogVisible">取 消</el-button>
        <el-button type="primary" @click="saveConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {getTenantId, getUserName} from '@/utils/auth'
  import {addOrUpdateActivityPic, deleteActivityPicById, getActivityPicById, getActivityPicList} from '@/api/tinysale/addActivity'
  import {upLoadFile} from '@/api/upLoadFile'

  export default {
    props: {
      activityId: {
        type: String,
        default() {
          return ''
        }
      }
    },
    data() {
      return {
        secondKeyWord: '',
        normal: [],
        pictureTableData: [],
        filterData: [],
        // 分页数据
        secondCurrentPage: 1,
        secondPageSize: 5,
        file: '',
        activityPicForm: {},
        // 新增活动弹框默认是否显示
        addActivityDialogVisible: false
      }
    },
    created() {
      this.getData()
    },
    methods: {
      // 动态生成表格编号
      typeIndex(index) {
        return index + (this.secondCurrentPage - 1) * this.secondPageSize + 1
      },
      getData() {
        getActivityPicList(this.activityId).then(res => {
          this.pictureTableData = res.data.items;
          this.filterData = res.data.items
        })
      },
      handleFilter() {
        this.pictureTableData = this.filterData.filter(item => {
          if (this.secondKeyWord && item.fileName.toLocaleLowerCase().indexOf(this.secondKeyWord.toLocaleLowerCase()) < 0) return false;
          return true
        })
      },
      // 分页设置
      handleCurrentChange(arg) {
        this.secondCurrentPage = arg
      },
      handleSizeChange(arg) {
        this.secondPageSize = arg
      },
      // 新增活动事件
      addsecondActivity() {
        this.$emit('save');
        setTimeout(() => {
          if (this.activityId) {
            this.addActivityDialogVisible = true
          }
        }, 200)
      },
      addUploadChange(file) {
        this.file = file.raw
      },
      submitUpload() {
        const fileForm = new FormData();
        fileForm.append('name', this.file.name);
        fileForm.append('uid', this.file.uid);
        fileForm.append('file', this.file);
        upLoadFile(fileForm).then(response => {
          this.$notify({
            title: '成功',
            message: '图片上传成功',
            type: 'success',
            duration: 2000
          });
          this.activityPicForm.fileId = response.data.id;
          this.activityPicForm.fileName = fileForm.get('name');
          this.activityPicForm.fileUrl = response.data.url
        })
      },
      // 新增图片取消事件
      addCancelDialogVisible() {
        this.activityPicForm = {};
        this.file = '';
        this.addActivityDialogVisible = false
        this.normal = [];
      },
      // 新增图片确定事件
      saveConfirm() {
        if (!this.activityPicForm.id) {
          this.activityPicForm.creator = getUserName();
          this.activityPicForm.tenantId = getTenantId();
          this.activityPicForm.activityId = this.activityId
        }
        if (this.activityPicForm.fileId) {
          addOrUpdateActivityPic(this.activityPicForm).then(res => {
            this.getData();
            this.$notify({
              title: '成功',
              message: '成功',
              type: 'success',
              duration: 2000
            })
          });
          this.file = '';
          this.addActivityDialogVisible = false
        } else {
          this.$message.error('请上传图片!')
        }
        // 清空内容
        this.activityPicForm = {};
        this.normal = [];
      },
      // 编辑图片列表事件
      editPicture(row) {
        getActivityPicById(row.id).then(res => {
          this.activityPicForm = res.data.item;
          this.addActivityDialogVisible = true
        })
      },
      // 删除图片列表
      deletePicture(row) {
        this.$confirm('确定要删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteActivityPicById(row.id).then(res => {
            this.getData();
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .headHint {
    color: rgb(52, 172, 228);
    padding: 10px 30px;
    background: #e4fafd;
    margin: 20px 0;
    overflow: hidden;
  }
</style>

